<template>
  <div class="dashboard-container">
    <!-- 顶部筛选栏 -->
    <el-card class="filter-card">
      <el-radio-group
        v-model="timeType"
        size="small"
        class="time-type"
        @change="handleTimeTypeChange"
      >
        <el-radio label="month">月度</el-radio>
        <el-radio label="year">年度</el-radio>
        <el-radio label="custom">自定义</el-radio>
      </el-radio-group>
      <!-- 月度/年度：单个日期选择器 -->
      <el-date-picker
        v-if="timeType !== 'custom'"
        v-model="singleDate"
        :type="timeType === 'month' ? 'month' : 'year'"
        placeholder="选择时间"
        value-format="yyyy-MM"
        style="margin-left: 10px; width: 150px"
        :key="timer + 1"
      />
      <!-- 自定义：日期范围选择器 -->
      <el-date-picker
        v-else
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
        style="margin-left: 10px; width: 240px"
        :key="timer + 2"
      />
      <el-button type="primary" icon="el-icon-search" @click="fetchData"
        >查询</el-button
      >
      <!-- <el-button type="primary" icon="el-icon-download" @click="exportData"
        >导出</el-button
      > -->
    </el-card>

    <!-- 第一行图表 -->
    <div class="chart-row">
      <!-- 预警类型数量统计（30%） -->
      <el-card class="chart-card-item" style="width: 30%">
        <div class="titleBox">
          <p class="title">预警类型数量统计</p>
        </div>
        <div
          ref="warningTypeChart"
          class="chart-item"
          style="width: 100%; height: 300px"
        ></div>
      </el-card>
      <!-- 地表水预警统计时间变化（70%） -->
      <el-card class="chart-card-item" style="width: 70%; margin-left: 20px">
        <div class="titleBox">
          <p class="title">地表水预警统计时间变化</p>
        </div>
        <div
          ref="surfaceWaterChart"
          class="chart-item"
          style="width: 100%; height: 300px"
        ></div>
      </el-card>
    </div>

    <!-- 第二行图表 -->
    <div class="chart-row" style="margin-top: 20px">
      <!-- 预警处理情况统计（50%） -->
      <el-card class="chart-card-item" style="width: 50%">
        <div class="titleBox">
          <p class="title">预警处理情况统计</p>
        </div>
        <div
          ref="warningHandleChart"
          class="chart-item"
          style="width: 100%; height: 300px"
        ></div>
      </el-card>
      <!-- 预警级别数量统计（50%） -->
      <el-card class="chart-card-item" style="width: 50%; margin-left: 20px">
        <div class="titleBox">
          <p class="title">预警级别数量统计</p>
        </div>
        <div
          ref="warningLevelChart"
          class="chart-item"
          style="width: 100%; height: 300px"
        ></div>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import dayjs from "dayjs";
import {
  getWarningTypeCount,
  getWarningTimeCount,
  getWarningHandleCount,
  getWarningLevelCount,
} from "@/api/waterWarningAnalysis";

export default {
  name: "Dashboard",
  data() {
    return {
      timer: new Date().getTime(),
      timeType: "month",
      singleDate: "",
      dateRange: [],
      warningTypeChart: null,
      surfaceWaterChart: null,
      warningHandleChart: null,
      warningLevelChart: null,
      // 存储接口返回的数据
      resData: {
        warningType: [],
        surfaceWater: {},
        warningHandle: {},
        warningLevel: {},
      },
    };
  },
  mounted() {
    this.initCharts();
    this.setDefaultTime();
    this.fetchData();
  },
  beforeDestroy() {
    if (this.warningTypeChart) {
      this.warningTypeChart.dispose();
    }
    if (this.surfaceWaterChart) {
      this.surfaceWaterChart.dispose();
    }
    if (this.warningHandleChart) {
      this.warningHandleChart.dispose();
    }
    if (this.warningLevelChart) {
      this.warningLevelChart.dispose();
    }
  },
  methods: {
    // 时间选择器切换
    setDefaultTime() {
      const now = dayjs();
      if (this.timeType === "month") {
        this.singleDate = now.format("YYYY-MM");
      } else if (this.timeType === "year") {
        this.singleDate = now.format("YYYY");
      } else {
        this.dateRange = [now.format("YYYY-MM-DD"), now.format("YYYY-MM-DD")];
      }
    },
    handleTimeTypeChange() {
      this.setDefaultTime();
    },
    getQueryTime() {
      let startTime = "",
        endTime = "";
      if (this.timeType === "month") {
        startTime = `${this.singleDate}-01`;
        endTime = dayjs(this.singleDate).endOf("month").format("YYYY-MM-DD");
      } else if (this.timeType === "year") {
        startTime = `${this.singleDate}-01-01`;
        endTime = `${this.singleDate}-12-31`;
      } else {
        startTime = this.dateRange[0];
        endTime = this.dateRange[1];
      }
      return { startTime, endTime };
    },
    fetchData() {
      const { startTime, endTime } = this.getQueryTime();
      console.log("查询时间：", startTime, endTime);
      let query = {
        startDay: startTime,
        endDay: endTime,
      };
      // 调用各接口获取数据并处理
      Promise.all([
        getWarningTypeCount(query),
        getWarningTimeCount(query),
        getWarningHandleCount(query),
        getWarningLevelCount(query),
      ])
        .then(([res1, res2, res3, res4]) => {
          console.log(">>>res1", res1);
          console.log(">>>res2", res2);
          console.log(">>>res3", res3);
          console.log(">>>res4", res4);

          this.resData.warningType = res1.data;
          this.resData.surfaceWater = res2.data;
          this.resData.warningHandle = res3.data;
          this.resData.warningLevel = res4.data;

          this.renderCharts();
        })
        .catch((error) => {
          console.error("接口请求错误：", error);
          this.$message.error("数据获取失败，请稍后再试");
        });
    },
    exportData() {
      const { startTime, endTime } = this.getQueryTime();
      console.log("导出时间：", startTime, endTime);
      this.$message.success("导出功能待对接后端接口");
    },
    initCharts() {
      this.initWarningTypeChart();
      this.initSurfaceWaterChart();
      this.initWarningHandleChart();
      this.initWarningLevelChart();
    },
    initWarningTypeChart() {
      this.warningTypeChart = echarts.init(this.$refs.warningTypeChart);
    },
    initSurfaceWaterChart() {
      this.surfaceWaterChart = echarts.init(this.$refs.surfaceWaterChart);
    },
    initWarningHandleChart() {
      this.warningHandleChart = echarts.init(this.$refs.warningHandleChart);
    },
    initWarningLevelChart() {
      this.warningLevelChart = echarts.init(this.$refs.warningLevelChart);
    },
    renderCharts() {
      this.renderWarningTypeChart();
      this.renderSurfaceWaterChart();
      this.renderWarningHandleChart();
      this.renderWarningLevelChart();
    },
    // 预警类型图表
    renderWarningTypeChart() {
      const seriesData = this.resData.warningType.map((item) => ({
        name: item.warnTypeName,
        value: item.dataCount,
      }));
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          borderColor: "#ddd",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          padding: 10,
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
        },
        series: [
          {
            name: "预警类型占比",
            type: "pie",
            radius: ["40%", "70%"],
            data: seriesData,
            label: {
              show: true,
              formatter: "{b}: {c}%",
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      this.warningTypeChart.setOption(option);
    },
    // 地表水预警图表
    renderSurfaceWaterChart() {
      const { typeList, dayList, dataCountList } = this.resData.surfaceWater;
      const seriesData = typeList.map((type, index) => ({
        name: type,
        data: dataCountList[index],
      }));
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          borderColor: "#ddd",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          padding: 10,
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
        },
        legend: {
          data: typeList,
          top: 0,
          textStyle: {
            fontSize: 12,
          },
        },
        xAxis: {
          type: "category",
          data: dayList,
        },
        yAxis: {
          type: "value",
          name: "预警次数",
        },
        series: seriesData.map((item) => ({
          type: "bar",
          name: item.name,
          data: item.data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        })),
      };
      this.surfaceWaterChart.setOption(option);
    },
    // 预警处理情况图表
    renderWarningHandleChart() {
      const { statusTypeList, statusCountList } = this.resData.warningHandle;
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ",
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          borderColor: "#ddd",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          padding: 10,
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
        },
        xAxis: {
          type: "category",
          data: statusTypeList,
        },
        yAxis: {
          type: "value",
          max: 100,
          name: "占比(%)",
        },
        series: [
          {
            name: "处理状态",
            type: "bar",
            data: statusCountList,
            // label: {
            //   show: true,
            //   position: "top",
            //   formatter: "{c}%",
            // },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      this.warningHandleChart.setOption(option);
    },
    // 预警级别图表
    renderWarningLevelChart() {
      const seriesData = this.resData.warningLevel.dataList.map((item) => ({
        name: item.warnLevelName,
        value: item.dataCount,
      }));
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          borderColor: "#ddd",
          borderWidth: 1,
          textStyle: {
            color: "#333",
          },
          padding: 10,
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
        },
        series: [
          {
            name: "预警级别占比",
            type: "pie",
            radius: ["40%", "70%"],
            data: seriesData,
            label: {
              show: true,
              formatter: "{b}: {c}%",
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      this.warningLevelChart.setOption(option);
    },
  },
};
</script>
<style lang="scss" scoped>
// 左右横排的标题和更多
.titleBox {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #dfe4ed;
  margin: 0 20px 20px 20px;
  position: relative;
  &::before {
    display: block;
    content: "";
    width: 3px;
    height: 16px;
    background: #307eff;
  }
  .title {
    font-size: 16px;
    color: #000;
    position: absolute;
    left: 10px;
    font-weight: 500;
    margin: 0;
  }
  .more {
    font-size: 16px;
    color: #999;
    cursor: pointer;
  }
}
</style>
<style scoped>
.dashboard-container {
  padding: 20px;
}
.filter-card {
  margin-bottom: 20px;
}
.time-type {
  margin-right: 10px;
}
.chart-row {
  display: flex;
}
.chart-card-item {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.chart-item {
  width: 100%;
  height: 100%;
}
</style>
